package com.bestcem.xm.user.grpc.client;

import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.om.grpc.v1.services.GetPlatformByCodeRequest;
import com.bestcem.xm.om.grpc.v1.services.GetPlatformByCodeResponse;
import com.bestcem.xm.om.grpc.v1.services.PlatformServiceGrpc;
import com.bestcem.xm.user.grpc.client.converter.UserPlatformGrpcConvert;
import com.bestcem.xm.user.grpc.client.dto.UserPlatformDTO;
import com.zy.dp.proto.base.v1.Code;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 用户合作商grpc接口
 *
 * @author qiongyu.cui <qiongyu.cui@idiaoyan.com>
 * @version v1.0
 * @date 2022/5/26 10:51
 */
@Slf4j
@Service("userPlatformGrpcService")
public class UserPlatformGrpcService {

    @GrpcClient(GrpcClientNames.DS_USER)
    private PlatformServiceGrpc.PlatformServiceBlockingStub stub;

    /**
     * 根据platformcode查询合作商信息
     *
     * @param platformCode code
     * @return void
     * @author cuiqiongyu <qiongyu.cui@idiaoyan.cn>
     * @date 2022/05/26 10:53
     */
    public UserPlatformDTO selectByPlatformCode(String platformCode) {
        if (log.isInfoEnabled()) {
            log.info("根据platformcode查询合作商信息参数：code:{}", platformCode);
        }
        if (StringUtils.isEmpty(platformCode)) {
            log.error("根据platformcode查询合作商信息错误，code不能为空");
            return null;
        }

        GetPlatformByCodeRequest.Builder builder = GetPlatformByCodeRequest.newBuilder();
        builder.setCode(platformCode);
        GetPlatformByCodeRequest request = builder.build();
        // 根据合作伙伴code查询单个平台信息
        GetPlatformByCodeResponse platformByCode = stub.getPlatformByCode(request);
        // 校验查询结果
        if (Code.ERROR_VALUE == platformByCode.getStatus().getCodeValue()) {
            log.error("根据platformcode查询合作商信息失败：dto:{} code:{}", platformByCode.getStatus().getMessage(), platformCode);
            return null;
        }

        return UserPlatformGrpcConvert.platformToDto(platformByCode.getPlatform());
    }

}
